/*
 * @Author: jiutian
 * @Date: 2023-02-03 19:25:20
 * @LastEditTime: 2023-03-10 19:19:07
 * @LastEditors:
 */
const db = require("../db");
const { changeObjType, formatTime, updateViews } = require("../utils");
const chalk = require("chalk");
const { server } = require("../project.config");

exports.saveBlog = (req, res) => {
  let { blogStr, blogTitle, blogText } = req.body;
  let sqlVal = {
    blog_title: blogTitle,
    blog_context: blogStr,
    blog_text: blogText,
    user_id: req.auth[0].id,
    create_time: formatTime(Date.now(), "YYYY-MM-DD HH:mm:ss"),
  };
  let sql = "insert into blogs set ? ";
  db.query(sql, sqlVal, (err, result) => {
    if (err) return res.cc(err);
    if (result.affectedRows !== 1) return res.cc("系统错误");
    res.send({
      code: 200,
      msg: "博客发布成功",
      data: null,
    });
  });
};

exports.getBlogList = (req, res) => {
  let { keyword, pageSize, pageNum } = req.query;
  let sql = "select * from blogs where status=1";
  let sqlVal = [];
  if (keyword) {
    sql += " and blog_title like ?";
    sqlVal.push(`%${keyword}%`);
  }

  let start = (pageNum - 1) * pageSize;
  sql += " order by id desc limit ? , ?";
  sqlVal.push(start);
  sqlVal.push(pageSize);
  db.query(sql, sqlVal, async (err, result) => {
    if (err) return res.cc(err);

    let data = [];
    for (let v of result) {
      let item = {
        ...v,
        create_time: formatTime(v.create_time, "YYYY-MM-DD HH:mm:ss"),
      };
      let user = await getUserName(item.user_id);
      item.username = user.username;
      item.phone_number = user.phone_number;
      data.push(changeObjType(item, "u"));
    }
    let total = await getTotal(sql, sqlVal);
    res.send({
      code: 200,
      msg: "获取成功",
      data: {
        list: data,
        pageNum,
        pageSize,
        total,
      },
    });
  });

  function getTotal(sql, sqlVal) {
    return new Promise((resolve, reject) => {
      let sql1 = sql.split("order")[0];
      sqlVal.splice(-2, 2);
      sql1 = sql1.replace("*", "count(*) as count");
      db.query(sql1, sqlVal, (err, result) => {
        if (err) return reject(err);
        resolve(result[0].count);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }

  function getUserName(userId) {
    return new Promise((resolve, reject) => {
      let sql =
        "select username , phone_number from users where id=? and status=1";
      db.query(sql, [userId], (err, result) => {
        if (err) return reject(err);
        resolve(result[0]);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.getBlogById = async (req, res) => {
  let { id } = req.query;
  let sql = "select * from blogs where id=? and status=1";
  let a = await updateViews("blogs", id);
  db.query(sql, [id], async (err, result) => {
    if (err) return res.cc(err);
    let data = changeObjType(result[0], "u");
    let user = await getUserName(data.userId);
    data.username = user.username;
    data.phoneNumber = user.phone_number;
    data.createTime = formatTime(data.createTime, "YYYY-MM-DD HH:mm:ss");
    res.send({
      code: 200,
      msg: "获取成功",
      data,
    });
  });

  function getUserName(userId) {
    return new Promise((resolve, reject) => {
      let sql =
        "select username , phone_number from users where id=? and status=1";
      db.query(sql, [userId], (err, result) => {
        if (err) return reject(err);
        resolve(result[0]);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.getCurrentUser = (req, res) => {
  let sql =
    "select id, username ,phone_number,user_pic from users where id=? and status=1";
  db.query(sql, [req.auth["0"].id], (err, result) => {
    if (err) return res.cc(err);
    let data = changeObjType(result[0], "u");
    res.send({
      code: 200,
      msg: "获取成功",
      data,
    });
  });
};

// 点赞
exports.operateLike = (req, res) => {
  let { type, id } = req.body;
  let sql = "";
  let sqlVal;
  if (type == "1") {
    sql = "insert into likes set ?";
    sqlVal = {
      user_id: req.auth["0"].id,
      blog_id: id,
    };
  } else {
    sql = "delete from likes where user_id=? and blog_id=?";
    sqlVal = [req.auth["0"].id, id];
  }

  db.query(sql, sqlVal, (err, result) => {
    if (err) return res.cc(err);
    if (result.affectedRows !== 1) return res.cc("系统错误");
    res.send({
      code: 200,
      msg: "操作成功",
    });
  });
};

exports.checkOperate = (req, res) => {
  let { id } = req.query;
  let sqlVal = [req.auth["0"].id, id];
  let data = {
    like: false,
    collect: false,
  };
  let sql = "select count(*) as count from likes where user_id=? and blog_id=?";
  db.query(sql, sqlVal, (err, result) => {
    if (err) return res.cc(err);
    if (result[0].count) data.like = true;
    let sql =
      "select count(*) as count from collect where user_id=? and blog_id=?";
    db.query(sql, sqlVal, (err, result) => {
      if (err) return res.cc(err);
      if (result[0].count) data.collect = true;

      res.send({
        code: 200,
        msg: "成功",
        data,
      });
    });
  });
};

// 收藏
exports.operateCollect = (req, res) => {
  let { type, id } = req.body;
  let sql = "";
  let sqlVal;
  if (type == "1") {
    sql = "insert into collect set ?";
    sqlVal = {
      user_id: req.auth["0"].id,
      blog_id: id,
    };
  } else {
    sql = "delete from collect where user_id=? and blog_id=?";
    sqlVal = [req.auth["0"].id, id];
  }

  db.query(sql, sqlVal, (err, result) => {
    if (err) return res.cc(err);
    if (result.affectedRows !== 1) return res.cc("系统错误");
    res.send({
      code: 200,
      msg: "操作成功",
    });
  });
};

exports.publishCommit = (req, res) => {
  let { id, context } = req.body;
  let sql = "insert into commits set ?";
  let sqlVal = {
    user_id: req.auth["0"].id,
    context,
    blog_id: id,
    create_time: formatTime(Date.now(), "YYYY-MM-DD HH:mm:ss"),
  };
  db.query(sql, sqlVal, (err, result) => {
    if (err) return res.cc(err);
    if (result.affectedRows !== 1) return res.cc("系统错误");
    res.send({
      code: 200,
      msg: "发布成功",
    });
  });
};

exports.getCommitList = (req, res) => {
  let { pageSize, pageNum, id } = req.query;
  let sql = "select * from commits where status=1 and blog_id=?";
  let sqlVal = [id];

  let start = (pageNum - 1) * pageSize;
  sql += " order by id desc limit ? , ?";
  sqlVal.push(start);
  sqlVal.push(pageSize);
  db.query(sql, sqlVal, async (err, result) => {
    if (err) return res.cc(err);

    let data = [];
    for (let v of result) {
      let item = {
        ...v,
        create_time: formatTime(v.create_time, "YYYY-MM-DD HH:mm:ss"),
      };
      let user = await getUserName(item.user_id);
      item.username = user.username;
      item.phone_number = user.phone_number;
      item.user_pic = user.user_pic;
      data.push(changeObjType(item, "u"));
    }
    let total = await getTotal(sql, sqlVal);
    res.send({
      code: 200,
      msg: "获取成功",
      data: {
        list: data,
        pageNum,
        pageSize,
        total,
      },
    });
  });

  function getTotal(sql, sqlVal) {
    return new Promise((resolve, reject) => {
      let sql1 = sql.split("order")[0];
      sqlVal.splice(-2, 2);
      sql1 = sql1.replace("*", "count(*) as count");
      db.query(sql1, sqlVal, (err, result) => {
        if (err) return reject(err);
        resolve(result[0].count);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }

  function getUserName(userId) {
    return new Promise((resolve, reject) => {
      let sql =
        "select username , phone_number , user_pic from users where id=? and status=1";
      db.query(sql, [userId], (err, result) => {
        if (err) return reject(err);
        resolve(result[0]);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.getBlogerList = (req, res) => {
  let { keyword } = req.query;
  let sql =
    "select id , username , phone_number , user_pic from users where username like ? or phone_number like ? and status=1";
  db.query(sql, [`%${keyword}%`, `%${keyword}%`], async (err, result) => {
    if (err) return res.cc(err);
    let data = [];
    for (let v of result) {
      let item = changeObjType(v, "u");
      let countResult = await getFocus(req.auth["0"].id, item.id);
      item.unreadCount = (await getNoRead(req.auth["0"].id, item.id)) || 0;
      if (countResult) {
        item.focus = true;
      }
      data.push(item);
    }

    res.send({
      code: 200,
      msg: "成功",
      data,
    });
  });

  function getFocus(authId, userId) {
    return new Promise((resolve, reject) => {
      let sql =
        "select count(*) as count from focus where user_id=? and focus_id=?";
      db.query(sql, [authId, userId], (err, result) => {
        if (err) return reject(err);
        resolve(result[0].count);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }

  function getNoRead(authId, userId) {
    return new Promise((resolve, reject) => {
      let sql =
        "select count(*) as count from message where is_read=0 and sender_id=? and replyer_id=? and status=1";
      db.query(sql, [userId, authId], (err, result) => {
        if (err) return reject(err);
        resolve(result[0].count);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.getMessageList = (req, res) => {
  let { replyerId, senderId, pageNum, pageSize } = req.query;
  let sql =
    "select * from message where status=1 and (sender_id=? and replyer_id=?) or (sender_id=? and replyer_id=?) order by id desc limit ? , ?";
  let sqlVal = [
    senderId,
    replyerId,
    replyerId,
    senderId,
    (pageNum - 1) * pageSize,
    pageSize,
  ];

  db.query(sql, sqlVal, async (err, result) => {
    if (err) return res.cc(err);
    let data = [];
    let total = await getTotal(sql, sqlVal);
    for (let v of result) {
      v.create_time = formatTime(v.create_time, "YYYY-MM-DD HH:mm:ss");
      data.push(changeObjType(v, "u"));
    }
    let a = await findMessage(replyerId, senderId);

    res.send({
      code: 200,
      msg: "成功",
      data: {
        list: data,
        pageNum,
        pageSize,
        total,
      },
    });
  });

  function getTotal(sql, sqlVal) {
    return new Promise((resolve, reject) => {
      let sql1 = sql.split("order")[0];
      sqlVal.splice(-2, 2);
      sql1 = sql1.replace("*", "count(*) as count");
      db.query(sql1, sqlVal, (err, result) => {
        if (err) return reject(err);
        resolve(result[0].count);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }

  function findMessage(replyerId, senderId) {
    return new Promise((resolve, reject) => {
      let sql =
        "select id from message where is_read=0 and status=1 and sender_id=? and replyer_id=?";
      db.query(sql, [replyerId, senderId], async (err, result) => {
        if (err) return reject(err);
        for (let v of result) {
          let updateResult = await updateRead(v.id);
          if (!updateResult) return reject("系统错误");
        }
        resolve(true);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }

  function updateRead(id) {
    return new Promise((resolve, reject) => {
      let sql = "update message set is_read=1 where status=1 and id=?";
      db.query(sql, [id], (err, result) => {
        if (err) return reject(err);
        resolve(true);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

// 关注
exports.operateFocus = (req, res) => {
  let { type, id } = req.body;
  let sql = "";
  let sqlVal;
  if (type == "1") {
    sql = "insert into focus set ?";
    sqlVal = {
      user_id: req.auth["0"].id,
      focus_id: id,
    };
  } else {
    sql = "delete from focus where user_id=? and focus_id=?";
    sqlVal = [req.auth["0"].id, id];
  }

  db.query(sql, sqlVal, (err, result) => {
    if (err) return res.cc(err);
    if (result.affectedRows !== 1) return res.cc("系统错误");
    res.send({
      code: 200,
      msg: "操作成功",
    });
  });
};

exports.getUnReadCount = (req, res) => {
  let { senderId } = req.query;
  let sql =
    "select count(*) as count from message where is_read=0 and sender_id=? and replyer_id=? and status=1";
  db.query(sql, [senderId, req.auth["0"].id], (err, result) => {
    if (err) return res.cc(err);
    res.send({
      code: 200,
      msg: "成功",
      data: {
        senderId,
        replyerId: req.auth["0"].id,
        unreadCount: result[0].count,
      },
    });
  });
};

exports.getPersonInfo = async (req, res) => {
  let { id } = req.query;
  let sql =
    "select id, username , phone_number , user_pic , views from users where id=? and status=1";
  let a = await updateViews("users", id);
  db.query(sql, [id], async (err, result) => {
    if (err) return res.cc(err);
    let data = {
      ...changeObjType(result[0], "u"),
      views: result[0].views,
      countObj: {
        帖子: await getTotalCount("blogs", id),
        点赞: await getTotalCount("likes", id),
        关注: await getTotalCount("focus", id),
        收藏: await getTotalCount("collect", id),
        评论: await getTotalCount("commits", id),
      },
    };
    res.send({
      code: 200,
      msg: "成功",
      data,
    });
  });

  function getTotalCount(dbName, userId) {
    return new Promise((resolve, reject) => {
      let sql = `select count(*) as count from ${dbName} where user_id=? and status=1`;
      db.query(sql, [userId], (err, result) => {
        if (err) return reject(err);
        resolve(result[0].count);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.getBlogListByUserId = (req, res) => {
  let { id, pageSize, pageNum } = req.query;
  let sql =
    "select * from blogs where status=1 and user_id=? order by id desc limit ? , ?";
  let sqlVal = [id, (pageNum - 1) * pageSize, pageSize];
  db.query(sql, sqlVal, async (err, result) => {
    if (err) return res.cc(err);
    let data = [];
    for (let v of result) {
      let user = await getUserName(v.user_id);
      v.create_time = formatTime(v.create_time, "YYYY-MM-DD HH:mm:ss");
      v.username = user.username;
      v.phoneNumber = user.phone_number;
      data.push(changeObjType(v, "u"));
    }
    let total = await getTotal(sql, sqlVal);
    res.send({
      code: 200,
      msg: "获取成功",
      data: {
        list: data,
        pageNum,
        pageSize,
        total,
      },
    });
  });

  function getTotal(sql, sqlVal) {
    return new Promise((resolve, reject) => {
      let sql1 = sql.split("order")[0];
      sqlVal.splice(-2, 2);
      sql1 = sql1.replace("*", "count(*) as count");
      db.query(sql1, sqlVal, (err, result) => {
        if (err) return reject(err);
        resolve(result[0].count);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }

  function getUserName(userId) {
    return new Promise((resolve, reject) => {
      let sql =
        "select username , phone_number from users where id=? and status=1";
      db.query(sql, [userId], (err, result) => {
        if (err) return reject(err);
        resolve(result[0]);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.deleteRowByid = (req, res) => {
  let { id } = req.body;
  let sql = "update blogs set status=0 where id=" + id;
  db.query(sql, async (err, result) => {
    if (err) return res.cc(err);
    let updateReulstA = await updateUserOpera("likes", id);
    let updateReulstB = await updateUserOpera("collect", id);
    let updateReulstC = await updateUserOpera("commits", id);
    res.send({
      code: 200,
      msg: "删除成功",
    });
  });

  function updateUserOpera(dbName, id) {
    return new Promise((resolve, reject) => {
      let sql = `update ${dbName} set status=0 where blog_id=?`;
      db.query(sql, [id], (err, result) => {
        if (err) return reject(err);
        resolve(true);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

function getListCommon(dbName, query) {
  return new Promise((resolve, reject) => {
    let { id, pageSize, pageNum } = query;
    let sql = `select * from ${dbName} where status=1 and user_id=? order by id desc limit ? , ?`;
    let sqlVal = [id, (pageNum - 1) * pageSize, pageSize];
    db.query(sql, sqlVal, async (err, result) => {
      if (err) return reject(err);
      let data = [];
      for (let v of result) {
        let user = await getUserName(v.user_id);
        if (v.create_time) {
          v.create_time = formatTime(v.create_time, "YYYY-MM-DD HH:mm:ss");
        }
        v.username = user.username;
        v.phoneNumber = user.phone_number;
        data.push(changeObjType(v, "u"));
      }
      let total = await getTotal(sql, sqlVal);
      let resData = {
        list: data,
        total,
      };
      resolve(resData);
    });
  }).catch((err) => {
    console.log(chalk.red(err));
  });

  function getTotal(sql, sqlVal) {
    return new Promise((resolve, reject) => {
      let sql1 = sql.split("order")[0];
      sqlVal.splice(-2, 2);
      sql1 = sql1.replace("*", "count(*) as count");
      db.query(sql1, sqlVal, (err, result) => {
        if (err) return reject(err);
        resolve(result[0].count);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }

  function getUserName(userId) {
    return new Promise((resolve, reject) => {
      let sql =
        "select username , phone_number from users where id=? and status=1";
      db.query(sql, [userId], (err, result) => {
        if (err) return reject(err);
        resolve(result[0]);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
}

exports.getLikeList = (req, res) => {
  getListCommon("likes", req.query)
    .then(async (resData) => {
      let { list, total } = resData;
      for (let v of list) {
        v.blog = await getBlog(v.blogId);
      }
      res.send({
        code: 200,
        msg: "成功",
        data: {
          list,
          pageNum: req.query.pageNum,
          pageSize: req.query.pageSize,
          total,
        },
      });
    })
    .catch((err) => {
      res.cc(err);
    });

  function getBlog(id) {
    return new Promise((resolve, reject) => {
      let sql = "select * from blogs where id=? and status=1";
      db.query(sql, [id], async (err, result) => {
        if (err) return reject(err);
        let data = changeObjType(result[0], "u");
        data.createTime = formatTime(data.createTime, "YYYY-MM-DD HH:mm:ss");
        resolve(data);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.getCollectList = (req, res) => {
  getListCommon("collect", req.query)
    .then(async (resData) => {
      let { list, total } = resData;
      for (let v of list) {
        v.blog = await getBlog(v.blogId);
      }
      res.send({
        code: 200,
        msg: "成功",
        data: {
          list,
          pageNum: req.query.pageNum,
          pageSize: req.query.pageSize,
          total,
        },
      });
    })
    .catch((err) => {
      res.cc(err);
    });

  function getBlog(id) {
    return new Promise((resolve, reject) => {
      let sql = "select * from blogs where id=? and status=1";
      db.query(sql, [id], async (err, result) => {
        if (err) return reject(err);
        let data = changeObjType(result[0], "u");
        data.createTime = formatTime(data.createTime, "YYYY-MM-DD HH:mm:ss");
        resolve(data);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.getFocusList = (req, res) => {
  getListCommon("focus", req.query)
    .then(async (resData) => {
      let { list, total } = resData;
      for (let v of list) {
        v.focus = await getFocus(v.focusId);
      }
      res.send({
        code: 200,
        msg: "成功",
        data: {
          list,
          pageNum: req.query.pageNum,
          pageSize: req.query.pageSize,
          total,
        },
      });
    })
    .catch((err) => {
      res.cc(err);
    });

  function getFocus(id) {
    return new Promise((resolve, reject) => {
      let sql =
        "select username , phone_number,user_pic from users where id=? and status=1";
      db.query(sql, [id], async (err, result) => {
        if (err) return reject(err);
        let data = changeObjType(result[0], "u");
        resolve(data);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.getCommitListPerson = (req, res) => {
  getListCommon("commits", req.query)
    .then(async (resData) => {
      let { list, total } = resData;
      for (let v of list) {
        v.blog = await getBlog(v.blogId);
      }
      res.send({
        code: 200,
        msg: "成功",
        data: {
          list,
          pageNum: req.query.pageNum,
          pageSize: req.query.pageSize,
          total,
        },
      });
    })
    .catch((err) => {
      res.cc(err);
    });

  function getBlog(id) {
    return new Promise((resolve, reject) => {
      let sql = "select * from blogs where id=? and status=1";
      db.query(sql, [id], async (err, result) => {
        if (err) return reject(err);
        let data = changeObjType(result[0], "u");
        data.createTime = formatTime(data.createTime, "YYYY-MM-DD HH:mm:ss");
        resolve(data);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.deleteCommitById = (req, res) => {
  let { id } = req.body;
  let sql = "update commits set status=0 where id=?";
  db.query(sql, [id], (err, result) => {
    if (err) return res.cc(err);
    res.send({
      code: 200,
      msg: "成功",
      data: null,
    });
  });
};

exports.globalSearch = (req, res) => {
  let { keyword } = req.query;
  new Promise(async (resolve, reject) => {
    let data = {
      blog: [],
      user: [],
    };
    let blogResult = await queryBlog(keyword);
    if (!blogResult) return reject("查询错误");
    data.blog = blogResult;

    let userResult = await queryUser(keyword);
    if (!userResult) return reject("查询错误");
    data.user = userResult;
    resolve(data);
  })
    .then((data) => {
      res.send({
        code: 200,
        msg: "成功",
        data,
      });
    })
    .catch((err) => {
      res.cc(err);
    });

  function queryBlog(keyword) {
    return new Promise((resolve, reject) => {
      let sql =
        "select * from blogs where status=1 and ( blog_title like ? or blog_text like ? )";
      db.query(sql, [`%${keyword}%`, `%${keyword}%`], (err, result) => {
        if (err) return reject(err);
        let list = [];
        result.forEach((v) => {
          let item = changeObjType(v, "u");
          list.push(item);
        });
        resolve(list);
      });
    }).catch((err) => {
      console.log(err);
    });
  }

  function queryUser(keyword) {
    return new Promise((resolve, reject) => {
      let sql =
        "select id,username , phone_number,user_pic from users where status=1 and ( username like ? or phone_number like ? )";
      db.query(sql, [`%${keyword}%`, `%${keyword}%`], (err, result) => {
        if (err) return reject(err);
        let list = [];
        result.forEach((v) => {
          let item = changeObjType(v, "u");
          list.push(item);
        });
        resolve(list);
      });
    }).catch((err) => {
      console.log(err);
    });
  }
};
